package com.quanquan.user.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.quanquan.user.configBeans.RabbitSender;
import com.quanquan.user.dto.MarketingRulesDTO;
import com.quanquan.user.entity.MarketingRules;
import com.quanquan.user.exception.UserLevelException;
import com.quanquan.user.repository.CommercialDoubleRepository;
import com.quanquan.user.repository.MarketingRulesRepository;
import com.quanquan.user.request.MarketingRulesRequest;
import commond.IntegralOutPut;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 功能描述:新用户福利逻辑层
 *
 * @ClassName: MarketingRulesService
 * @Author: xiaoqianh丶
 * @Date: 2019-05-24 17:17
 * @Version: V1.0
 */
@Service
public class MarketingRulesService {

    private final RabbitSender rabbitSender;
    private final RedisTemplate redisTemplate;
    private final MarketingRulesRepository marketingRulesRepository;

    private final CommercialDoubleService commercialDoubleService;
    private final CommercialDoubleRepository commercialDoubleRepository;

    public MarketingRulesService(RedisTemplate redisTemplate, MarketingRulesRepository marketingRulesRepository, RabbitSender rabbitSender, CommercialDoubleRepository commercialDoubleRepository, CommercialDoubleService commercialDoubleService) {
        this.redisTemplate = redisTemplate;
        this.marketingRulesRepository = marketingRulesRepository;
        this.rabbitSender = rabbitSender;
        this.commercialDoubleRepository = commercialDoubleRepository;
        this.commercialDoubleService = commercialDoubleService;
    }

    public void checkoutWelfareRule(String userId) {

        Boolean newMemberCoupom = false;
        Boolean newMemberIntegral = false;
        Boolean newMemberParkingCoupom = false;
        Boolean consumptionQuota = false;
        String coupomCountNum = null;
        String coupomIds = null;
        String rewardIntegral = null;
        String coupomParkingCountNum = null;
        String coupomParkingIds = null;
        //查询积分规则(先查缓存，没有缓存后查数据库)
        BoundHashOperations<String, String, Object> redisMarketingRule = redisTemplate.boundHashOps("marketingRules");
        if (redisMarketingRule.size() > 0) {
            newMemberCoupom = (Boolean) redisMarketingRule.get("newMemberCoupom");
            newMemberIntegral = (Boolean) redisMarketingRule.get("newMemberIntegral");
            newMemberParkingCoupom = (Boolean) redisMarketingRule.get("newMemberParkingCoupom");
            coupomCountNum = redisMarketingRule.get("coupomCountNum").toString();
            coupomIds = redisMarketingRule.get("coupomIds").toString();
            rewardIntegral = redisMarketingRule.get("rewardIntegral").toString();
            coupomParkingCountNum = redisMarketingRule.get("coupomParkingCountNum").toString();
            coupomParkingIds = redisMarketingRule.get("coupomParkingIds").toString();
        } else {
            List<MarketingRules> all = marketingRulesRepository.findAll();
            MarketingRules marketingRules = all.get(0);

            //优惠券福利
            newMemberCoupom = marketingRules.getNewMemberCoupom();
            coupomCountNum = marketingRules.getCoupomCountNum();
            coupomIds = marketingRules.getCoupomIds();
            //积分福利
            newMemberIntegral = marketingRules.getNewMemberIntegral();
            rewardIntegral = marketingRules.getRewardIntegral();
            //停车券福利
            newMemberParkingCoupom = marketingRules.getNewMemberParkingCoupom();
            coupomParkingCountNum = marketingRules.getCoupomParkingCountNum();
            coupomParkingIds = marketingRules.getCoupomParkingIds();


            BoundHashOperations<String, String, Object> boundHashOperations = redisTemplate.boundHashOps("marketingRules");
            boundHashOperations.put("newMemberCoupom", newMemberCoupom); //是否推送优惠券
            boundHashOperations.put("newMemberIntegral", newMemberIntegral); //是否奖励积分
            boundHashOperations.put("newMemberParkingCoupom", newMemberParkingCoupom); //是否推送停车券
            boundHashOperations.put("consumptionQuota", consumptionQuota); //是否推送停车券
            boundHashOperations.put("coupomCountNum", coupomCountNum);
            boundHashOperations.put("coupomIds", coupomIds);
            boundHashOperations.put("rewardIntegral", rewardIntegral);
            boundHashOperations.put("coupomParkingCountNum", coupomParkingCountNum);
            boundHashOperations.put("coupomParkingIds", coupomParkingIds);


        }

        //是否要给积分
        if (newMemberIntegral) {
            //调用队列
            sountIntegral(rewardIntegral, userId);
        }
        //是否要推优惠券
        if (newMemberCoupom) {
            List<String> list = new ArrayList<>();
            if (coupomIds.contains(";")) {
                String[] split = coupomIds.split(";");
                list = Arrays.asList(split);
            } else {
                list.add(coupomIds);
            }
            List<String> userIds = new ArrayList<>();
            userIds.add(userId);
            //调用队列
            sendCoupomMQ(list, coupomCountNum, userIds);

        }

        //是否要推停车券
        if (newMemberParkingCoupom) {
            //调用队列
            List<String> list = new ArrayList<>();
            if (coupomParkingIds.contains(";")) {
                String[] split = coupomParkingIds.split(";");
                list = Arrays.asList(split);
            } else {
                list.add(coupomParkingIds);
            }
            List<String> userIds = new ArrayList<>();
            userIds.add(userId);
            //调用队列
            sendCoupomMQ(list, coupomParkingCountNum, userIds);
        }

    }


    //添加积分明细
    private void sountIntegral(String integralPoint, String userId) {
        IntegralOutPut integralOutPut = new IntegralOutPut();
        integralOutPut.setConsumeType("registered");
        integralOutPut.setForeignKeyId(userId);
        integralOutPut.setIntegralPoint(integralPoint);
        integralOutPut.setUserId(userId);
        integralOutPut.setOrderNum(userId);
        integralOutPut.setSource("新会员注册福利");
        integralOutPut.setTradeAction(0);
        integralOutPut.setTradingContent("新会员注册福利");

        String exchange = "integral.exchange";
        String routingKey = "integral.registered";
        rabbitSender.sendMessageToMQ(integralOutPut, null, exchange, routingKey);
    }

    //发送优惠券
    private void sendCoupomMQ(List<String> coupomIds, String coupomNum, List<String> userIds) {
        Map<String, Object> properties = new HashMap<>();
        properties.put("userIds", userIds);
        properties.put("coupomIds", coupomIds);
        properties.put("coupomNum", coupomNum);

        String exchange = "coupon.exchange";
        String routingKey = "coupon.sendCoupon";

        rabbitSender.sendMessageToMQ("用户发券", properties, exchange, routingKey);
    }

    /**
     * 更新
     *
     * @param request
     * @return
     */
    public String updateRule(MarketingRulesRequest request) throws UserLevelException {
        MarketingRules marketingRules = marketingRulesRepository.findByRuleId(request.getId());
        if (marketingRules == null) {
            throw new UserLevelException("规则不存在");
        }
        BeanUtil.copyProperties(request, marketingRules, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        marketingRulesRepository.saveAndFlush(marketingRules);


        //更新缓存
        redisIntegralRuleDouble(marketingRules);
        return "更新规则成功";
    }

    private void redisIntegralRuleDouble(MarketingRules marketingRules) {


        Boolean newMemberCoupom = marketingRules.getNewMemberCoupom();
        String coupomCountNum = marketingRules.getCoupomCountNum();
        String coupomIds = marketingRules.getCoupomIds();
        //积分福利
        Boolean newMemberIntegral = marketingRules.getNewMemberIntegral();
        String rewardIntegral = marketingRules.getRewardIntegral();
        //停车券福利
        Boolean newMemberParkingCoupom = marketingRules.getNewMemberParkingCoupom();
        String coupomParkingCountNum = marketingRules.getCoupomParkingCountNum();
        String coupomParkingIds = marketingRules.getCoupomParkingIds();
        Boolean consumptionQuota = marketingRules.getConsumptionQuota();

        BoundHashOperations<String, String, Object> boundHashOperations = redisTemplate.boundHashOps("marketingRules");
        boundHashOperations.put("newMemberCoupom", newMemberCoupom); //是否推送优惠券
        boundHashOperations.put("newMemberIntegral", newMemberIntegral); //是否奖励积分
        boundHashOperations.put("newMemberParkingCoupom", newMemberParkingCoupom); //是否推送停车券
        boundHashOperations.put("consumptionQuota", consumptionQuota); //是否推送停车券
        boundHashOperations.put("coupomCountNum", coupomCountNum);
        boundHashOperations.put("coupomIds", coupomIds);
        boundHashOperations.put("rewardIntegral", rewardIntegral);
        boundHashOperations.put("coupomParkingCountNum", coupomParkingCountNum);
        boundHashOperations.put("coupomParkingIds", coupomParkingIds);

    }

    /**
     * 查看列表
     *
     * @return
     */
    public List<MarketingRulesDTO> list() {
        List<MarketingRulesDTO> marketingRulesDTOS = new LinkedList<>();
        List<MarketingRules> marketingRules = marketingRulesRepository.findAlls();
        for (MarketingRules marketingRules1 : marketingRules) {
            MarketingRulesDTO marketingRulesDTO = new MarketingRulesDTO();
            BeanUtils.copyProperties(marketingRules1, marketingRulesDTO);
            marketingRulesDTOS.add(marketingRulesDTO);
        }
        return marketingRulesDTOS;
    }


    /**
     * 通过id查详情
     *
     * @return
     */
    public MarketingRulesDTO findByRuleId(String id) {
        MarketingRules marketingRules = marketingRulesRepository.findByRuleId(id);
        if (marketingRules == null) {
            return null;
        }
        MarketingRulesDTO marketingRulesDTO = new MarketingRulesDTO();
        BeanUtils.copyProperties(marketingRules, marketingRulesDTO);
        return marketingRulesDTO;
    }


    /**
     * 开启开关
     */
    public String changeConsumptionQuota() {
        List<MarketingRules> all = marketingRulesRepository.findAll();
        MarketingRules marketingRules = all.get(0);
        if (marketingRules.getConsumptionQuota()) {
            marketingRules.setConsumptionQuota(false);
        } else {
            marketingRules.setConsumptionQuota(true);
        }
        marketingRulesRepository.save(marketingRules);
        redisIntegralRuleDouble(marketingRules);
        return "设置成功";
    }
}
